package com.kuqi;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.kuqi.adapter.ChapterTitleAdapter;
import com.kuqi.adapter.ReadContentAdapter;
import com.kuqi.core.AppActivity;
import com.kuqi.entitiy.BrightUtil;
import com.kuqi.entitiy.Chapter;
import com.kuqi.entitiy.ReadSetting;
import com.kuqi.presenters.ReadPresenter;
import com.kuqi.utils.DialogCreator;
import com.kuqi.utils.StringHelper;
import java.util.ArrayList;
import java.util.List;

public class ReadActivity extends AppActivity {

    // 辅助代理部分功能，并监听生命周期的代理
    private ReadPresenter presenter;

    // 页面控件相关
    private DrawerLayout dl_read_activity; // 拥有侧滑菜单的控制面板
    private RecyclerView rv_content; // 阅读内容的主要显示区
    private TextView tv_book_list;  //隐藏在左侧的目录栏目
    private TextView tv_chapter_sort;
    private LinearLayout ll_chapter_list_view;
    private ListView lv_chapter_list;  // 当前显示中的章节List
    private ProgressBar pb_loading; //页面加载loading

    // 阅读内容显示适配器
    private ReadContentAdapter readContentAdapter;
    // 主视图显示管理者
    private LinearLayoutManager linearLayoutManager;
    // 章节内容适配器
    private ChapterTitleAdapter chapterTitleAdapter;
    // 用于加载完成前的加载提示遮罩
    private RelativeLayout rl_book_Launch;
    private ImageView iv_launch_center;

    // 系统显示设置窗体
    Dialog mSettingDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.read_page);

        // 隐藏标题栏
        hideActionBar();

        // 获取诸多控件对象
        dl_read_activity = findViewById(R.id.dl_read_activity);
        rv_content = findViewById(R.id.rv_content);
        tv_book_list = findViewById(R.id.tv_book_list);
        tv_chapter_sort = findViewById(R.id.tv_chapter_sort);
        ll_chapter_list_view = findViewById(R.id.ll_chapter_list_view);
        lv_chapter_list = findViewById(R.id.lv_chapter_list);
        pb_loading = findViewById(R.id.pb_loading);
        rl_book_Launch = findViewById(R.id.rl_book_Launch);
        iv_launch_center = findViewById(R.id.iv_launch_center);

        // 优先给提示添加一个动态gif
        Glide.with(this).asGif().load(R.drawable.book_launch).into(iv_launch_center);

        // 构建辅助代理程序
        // TODO 由于界面的部分显示是回调之后再渲染的，这里会触发一个不影响功能的 No adapter attached; skipping layout 异常
        presenter = new ReadPresenter(this, getLifecycle(),msgHandler,this);
    }


    /**
     * 初始化基础功能，仅执行一次
     */
    private void initialization(){
        // 初始化或者刷新主视图 即文本显示视图
        initOrRefreshMainContent();
        // 初始化章节目录视图 即目录列表
        initChapterTitleList();

        // 对象设置点击事件
        lv_chapter_list.setOnItemClickListener(lvChapterListClick); // 目录点击事件
        tv_chapter_sort.setOnClickListener(tvChapterSortClick); // 正序倒序事件
        rv_content.addOnScrollListener(rvContentScrolled); // 主内容区域滑动事件

        // 允许手动滑动打开目录
        dl_read_activity.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

        // 初始化一些颜色和格式
        initColorStyle();
    }



    /**
     * 目录列表中 章节点击事件
     */
    AdapterView.OnItemClickListener lvChapterListClick = new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            dl_read_activity.closeDrawer(GravityCompat.START); // 关闭侧滑菜单
            lv_chapter_list.setSelection(position); // 目录列表跳转显示选中项
            chapterTitleAdapter.setCurChapterPosition(position); // 适配器记录当前章节内容选中项
            pb_loading.setVisibility(View.VISIBLE); // 显示读取中提示图标
            Chapter chapter = presenter.getBookChapter(position); // 获取书籍实体信息
            if (StringHelper.isEmpty(chapter.getChapterContent())) { // 如果本地缓存中章节正文为空
                Log.e("Read Activity","警告，当前点击的章节没有内容！");
                pb_loading.setVisibility(View.GONE);
            }else{
                pb_loading.setVisibility(View.GONE); // 隐藏读取中提示图标
                rv_content.scrollToPosition(position);
            }
            Log.e("Read Activity", "点击章节列表，章节名：" + chapter.getChapterName());
        }
    };


    /**
     * 目录列表中 点击正序或者倒序
     */
    View.OnClickListener tvChapterSortClick = new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            if (presenter.curSortflag == 1) { //当前倒序 显示按钮为正序，点击切换为正序
                tv_chapter_sort.setText(getString(R.string.positive_sort));
                presenter.curSortflag = 0;
                ArrayList<Chapter> bookChapters = presenter.bookChapters;
                chapterTitleAdapter = new ChapterTitleAdapter(
                        getApplicationContext(), R.layout.listview_chapter_title_item, bookChapters);
            } else { //当前正序 显示按钮为倒叙，点击切换为倒序
                tv_chapter_sort.setText(getString(R.string.inverted_sort));
                presenter.curSortflag = 1;
                ArrayList<Chapter> mInvertedOrderChapters = presenter.invertedOrderChapters;
                chapterTitleAdapter = new ChapterTitleAdapter(
                        getApplicationContext(), R.layout.listview_chapter_title_item, mInvertedOrderChapters);
            }
            lv_chapter_list.setAdapter(chapterTitleAdapter);
        }
    };


    /**
     * 初始化或者刷新主视图 即文本显示视图
     */
    private void initOrRefreshMainContent(){
        if (readContentAdapter == null) {  // 如果正文数据管理器不存在，就创建它
            //构建线性布局
            linearLayoutManager = new LinearLayoutManager(this);
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            rv_content.setLayoutManager(linearLayoutManager);
            // 自定义阅读内容适配器
            readContentAdapter = new ReadContentAdapter(
                    this, R.layout.listview_chapter_content_item, presenter.bookChapters, presenter.mBook);
            // 给自定义适配器设置触摸功能
            readContentAdapter.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    presenter.touchPositionY = event.getRawY();
                    return false;
                }
            });
            // 给自定义适配器设置点击监听
            readContentAdapter.setOnClickItemListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (presenter.touchPositionY > presenter.settingOnClickValidFrom
                            && presenter.touchPositionY < presenter.settingOnClickValidTo) { // 点击在居中位置
                        Log.e("readActivity", "点击居中位置！");
                        showSettingView(); //显示配置视图
                    } else if (presenter.touchPositionY > presenter.settingOnClickValidTo) { // 下半区域，向下滑动
                        Log.e("readActivity", "点击下半区位置！");
                        rv_content.scrollBy(0, getCurrentActivityHeight());
                    } else if (presenter.touchPositionY < presenter.settingOnClickValidFrom) { // 上半区域，向上滑动
                        Log.e("readActivity", "点击上半区位置！");
                        rv_content.scrollBy(0, -getCurrentActivityHeight());
                    }
                }
            });
            rv_content.setAdapter(readContentAdapter);
        } else { // 数据管理器已经存在，通知其数据刷新
            readContentAdapter.notifyDataSetChanged();
            // TODO 每次都会跳转到章节末尾，这点需要注意
            int selectItem = chapterTitleAdapter.getCurChapterPosition();
            Log.e("list选中条目：", String.valueOf(selectItem));
            rv_content.scrollToPosition(selectItem);
        }
    }


    /**
     * 初始化章节目录视图
     */
    private void initChapterTitleList(){
        if (presenter.getReadConfig().isDayStyle()) {
            tv_book_list.setTextColor(getResources().getColor(presenter.getReadConfig().getReadWordColor()));
            tv_chapter_sort.setTextColor(getResources().getColor(presenter.getReadConfig().getReadWordColor()));
            ll_chapter_list_view.setBackgroundResource(presenter.getReadConfig().getReadBgColor());
        } else {
            tv_book_list.setTextColor(getResources().getColor(R.color.sys_night_word));
            tv_chapter_sort.setTextColor(getResources().getColor(R.color.sys_night_word));
            ll_chapter_list_view.setBackgroundResource(R.color.sys_night_bg);
        }

        int selectedPosition; // 当前正在显示的章节是哪一个
        int chapterNum = presenter.bookChapters.size(); // 总章节数量
        if (presenter.curSortflag == 0) { // 正序
            chapterTitleAdapter = new ChapterTitleAdapter(this, R.layout.listview_chapter_title_item, presenter.bookChapters);
            selectedPosition = linearLayoutManager.findFirstVisibleItemPosition(); // 获取当前可视区域顶格的item为当前chapter
            if (selectedPosition < 0) selectedPosition = 0;
            if (selectedPosition > chapterNum - 1) selectedPosition = chapterNum - 1;
            chapterTitleAdapter.setCurChapterPosition(selectedPosition);
            Log.e("正序", "当前选中的章节为：" + selectedPosition);
        } else { // 倒序
            chapterTitleAdapter = new ChapterTitleAdapter(this, R.layout.listview_chapter_title_item, presenter.invertedOrderChapters);
            selectedPosition = linearLayoutManager.findFirstVisibleItemPosition(); // 获取当前可视区域顶格的item为当前chapter
            if (selectedPosition < 0) selectedPosition = 0;
            if (selectedPosition > chapterNum - 1) selectedPosition = chapterNum - 1;
            chapterTitleAdapter.setCurChapterPosition(selectedPosition);
            Log.e("倒序", "当前选中的章节为：" + selectedPosition);
        }
        lv_chapter_list.setAdapter(chapterTitleAdapter);
        lv_chapter_list.setSelection(selectedPosition); // 当前list显示选中项，和我们的setCurChapterPosition对应
    }


    /**
     * 主内容区域上下滑动触发事件
     */
    RecyclerView.OnScrollListener rvContentScrolled = new RecyclerView.OnScrollListener(){
        // 记录当前顶格的item编号，每当变化时检测缓存并且更新目录选中条目的色彩。
        int currentTopItem = -1;

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, final int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //int visibleItemCount = mLinearLayoutManager.getChildCount(); // 可见区域有几个子项
            //int totalItemCount = mLinearLayoutManager.getItemCount(); // 总共有多少个子项
            int fistItem = linearLayoutManager.findFirstVisibleItemPosition(); // 获取第一个可见子项position
            if(currentTopItem != fistItem){ // 显示的顶部条目发生变化，缓存并修改目录样式
                currentTopItem = fistItem;
                // View itemView = mLinearLayoutManager.findViewByPosition(fistItem);
                lv_chapter_list.setSelection(fistItem); // 当前list选中项，和我们的setCurChapterPosition对应
                chapterTitleAdapter.setCurChapterPosition(fistItem); // 同步更新到adapter里去
                Log.e("scroll", "当前scroll的item位置顶格的是：" + fistItem);
            }
        }
    };



    /**
     * 初始化一些主体颜色和格式
     */
    private void initColorStyle(){
        ReadSetting config = presenter.getReadConfig();
        if (config.isDayStyle()) { // 日间效果还是夜间效果
            dl_read_activity.setBackgroundResource(config.getReadBgColor());
        } else {
            dl_read_activity.setBackgroundResource(R.color.sys_night_bg);
        }
        if (!config.isBrightFollowSystem()) { // 是否跟随系统亮度
            BrightUtil.setBrightness(this, config.getBrightProgress());
        }
    }


    /**
     * 点击页面中间，显示设置视图（无则构建）
     */
    private void showSettingView() {
        // 计算当前章节的阅读进度
        int progress = 100;
        if(presenter.bookChapters.size() > 1){
            progress = linearLayoutManager.findLastVisibleItemPosition() * 100 / (presenter.bookChapters.size() - 1);
        }

        if (mSettingDialog != null) {
            // TODO 这里需要一个更新进度条方法
            mSettingDialog.show();
        } else {
            mSettingDialog = DialogCreator.createReadSetting(this, presenter.getReadConfig().isDayStyle(), progress,
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {//返回
                            // mReadActivity.finish();
                            Log.e("read Dialog", "你点了什么？");
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {//上一章
                            int curPosition = linearLayoutManager.findLastVisibleItemPosition();
                            if (curPosition > 0) {
                                rv_content.scrollToPosition(curPosition - 1);
                            }
                            else{
                                Toast.makeText(getApplicationContext(), "已经是第一章！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {//下一章
                            int curPosition = linearLayoutManager.findLastVisibleItemPosition();
                            if (curPosition < presenter.bookChapters.size() - 1) {
                                rv_content.scrollToPosition(curPosition + 1);
                            }else{
                                Toast.makeText(getApplicationContext(), "已经是最后一章！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {//目录
                            dl_read_activity.openDrawer(GravityCompat.START);
                            mSettingDialog.dismiss();
                            Toast.makeText(getApplicationContext(), "点击显示目录！", Toast.LENGTH_SHORT).show();
                        }
                    }, new DialogCreator.OnClickNightAndDayListener() {
                        @Override
                        public void onClick(Dialog dialog, View view, boolean isDayStyle) {//日夜切换
                            // TODO changeNightAndDaySetting(isDayStyle);
                            Toast.makeText(getApplicationContext(), "点击日夜间切换！", Toast.LENGTH_SHORT).show();
                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {//设置
                            // TODO showSettingDetailView();
                            Toast.makeText(getApplicationContext(), "点击详细设置！", Toast.LENGTH_SHORT).show();
                        }
                    }, new SeekBar.OnSeekBarChangeListener() {//阅读进度
                        @Override
                        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                            // pb_loading.setVisibility(View.VISIBLE);
                            // final int chapterNum = (presenter.bookChapters.size() - 1) * i / 100;
                            // 更新章节内容，这里没有设置callback，会实用默认处理方法
                            // presenter.getChapterContent(presenter.bookChapters.get(chapterNum), null);
                            // TODO 这里需要设置一个按照进度跳转方法
                        }

                        @Override
                        public void onStartTrackingTouch(SeekBar seekBar) { }

                        @Override
                        public void onStopTrackingTouch(SeekBar seekBar) { }
                    }
                    , null // 我们现在不提供所谓语音阅读功能
                    , new DialogCreator.OnClickDownloadAllChapterListener() {
                        @Override
                        public void onClick(Dialog dialog, View view, TextView tvDownloadProgress) {
                            Toast.makeText(getApplicationContext(), "点击缓存全部章节！", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }


    @SuppressLint("HandlerLeak")
    private final Handler msgHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ReadPresenter.FINISH_CATALOGUE: // 优先初始化及对比数据，只有这一步完成了才能执行其他功能
                    Log.e("readActivity-msgHandler", "初始化缓存完成回调！");
                    initialization(); // 数据缓存完成，启动初始化
                    // 关闭掉加载界面
                    rl_book_Launch.setVisibility(View.GONE);
                    break;
                default:
                    Log.e("readActivity-msgHandler", "未知的msgKey : "  + msg.what);
                    break;
            }
        }
    };

}
